package com.lsh.oms.core.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.exception.BusinessException;
import com.lsh.oms.core.enums.PayChannel;
import com.lsh.oms.core.enums.PayWay;
import com.lsh.oms.core.model.payment.BillPaymentInfo;
import com.lsh.oms.core.model.payment.PayRequestDTO;
import com.lsh.oms.core.utils.IdGenerator;
import com.lsh.oms.core.utils.http.HttpClientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Project Name: lsh-groupon
 *
 * @author peter
 * @date 17/7/1
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Service
@Slf4j
public class PaymentProxy {

    private static final String PAY_PAYMENT_URL = "/pay/payment/prepayment";
    private static final String PAY_PAYMENT_QUERY_URL = "/pay/payment/query";
    private static final String OMS_PAYMENT_NOTIFY = "/api/oms/java/v1/order/pay/online/notify";
    private static final String PAY_PAYMENT_QUERY_INFO_URL = "/pay/payment/paydealinfo";

    /**
     * 请求支付系统的url
     */
    @Value("${pay.base.url}")
    private String payBaseUrl;

    /**
     * 支付回调的url
     */
    @Value("${pay.notify.url}")
    private String payNotifyUrl;

    public JSONObject prePay(BillPaymentInfo billPaymentInfo) throws BusinessException {

        String paySource = billPaymentInfo.getPayWay();
        String payChannel = billPaymentInfo.getPayChannelType() + "";
        String openid = billPaymentInfo.getOpenId();
        String returnUrl = billPaymentInfo.getReturnUrl();
        String tradeId = billPaymentInfo.getPayTradeId();
        String uid = billPaymentInfo.getUid();
        BigDecimal orderAmount = billPaymentInfo.getPayAmount();

        String ext = billPaymentInfo.getExt();
        Integer system = null;
        Integer systemChannel = null;
        if (!StringUtils.isBlank(ext)) {
            JSONObject extJson = JSON.parseObject(ext);

            system = extJson.getInteger("system");
            systemChannel = extJson.getInteger("systemChannel");
        }

        if (system == null) {
            system = 1;
        }

        if (systemChannel == null) {
            systemChannel = 1;
        }

        PayRequestDTO payRequestDTO = new PayRequestDTO();
        payRequestDTO.setRequestAmount(orderAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString())
                .setPaySource(PayWay.getName(Integer.valueOf(paySource)))
                .setSystem(system)
                .setSystemChannel(systemChannel)
                .setTradeId(tradeId)
                .setChannelType(payChannel)
                .setVenderId(billPaymentInfo.getVenderId())
                .setNotifyUrl(payNotifyUrl + OMS_PAYMENT_NOTIFY);
        // 微信支付
        if (PayChannel.WX.getCode().equals(payChannel)) {
            payRequestDTO.setOpenid(openid);
        }

        if (PayChannel.ON_CREDIT.getCode().equals(payChannel)
                || PayChannel.PRE_PAYMENT.getCode().equals(payChannel)
                || PayChannel.BALANCE_PAYMENT.getCode().equals(payChannel)) {

            payRequestDTO.setUid(uid);
        }

        JSONObject responseJson = null;
        try {
            if (StringUtils.isNotBlank(returnUrl)) {
                payRequestDTO.setReturnUrl(URLEncoder.encode(returnUrl, "UTF-8"));
            }

            String requestBody = JSON.toJSONString(payRequestDTO);
            log.info("[ {} - requestBody is ] {} ", tradeId, requestBody);
            String response = HttpClientTemplate.doPostBody(payBaseUrl + PAY_PAYMENT_URL, requestBody, this.getRequestHead(billPaymentInfo.getVenderId()));

            log.info("[ {} - response is ] {}", tradeId, response);
            if (StringUtils.isBlank(response)) {
                return null;
            }
            JSONObject prepayResponse = JSON.parseObject(response);
            String ret = prepayResponse.getString("ret");
            if (ret.equals("0")) {
                responseJson = prepayResponse.getJSONObject("content");
                log.info("{} - responseJson is {}.", tradeId, responseJson);
            }
        } catch (Exception e) {
            log.error("请求支付失败", e);
        }

        return responseJson;
    }


    private Map<String, String> getRequestHead(Long venderId) {

        Map<String, String> head = new HashMap<>(5);
        head.put("api-version", "1.1");
        head.put("sign", String.valueOf(IdGenerator.genId()));
        head.put("platform", "oms");
        head.put("venderId", venderId + "");

        return head;
    }

    public JSONObject queryStatus(String tradeId, String payPaymentNo, Long venderId) throws BusinessException {
        JSONObject jsonObject = new JSONObject(3);
        if (StringUtils.isNotBlank(tradeId)) {
            jsonObject.put("trade_id", tradeId);
        }
        if (StringUtils.isNotBlank(payPaymentNo)) {
            jsonObject.put("pay_payment_no", payPaymentNo);
        }

        JSONObject responseJson = null;

        try {

            log.info("[ {} - requestBody is ] {} ", tradeId, jsonObject.toJSONString());
            String response = HttpClientTemplate.doPostBody(payBaseUrl + PAY_PAYMENT_QUERY_URL, jsonObject.toJSONString(), this.getRequestHead(venderId));

            log.info("[ {} - response is ] {}", tradeId, response);
            if (StringUtils.isBlank(response)) {
                return null;
            }
            JSONObject prepayResponse = JSON.parseObject(response);
            String ret = prepayResponse.getString("ret");
            if (ret.equals("0")) {
                responseJson = prepayResponse.getJSONObject("content");

                log.info("{} - responseJson is {}.", tradeId, responseJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseJson;
    }

    public JSONObject queryPayInfo(String tradeId, String payPaymentNo, Long venderId) throws BusinessException {
        JSONObject jsonObject = new JSONObject(3);
        if (StringUtils.isNotBlank(tradeId)) {
            jsonObject.put("trade_id", tradeId);
        }
        if (StringUtils.isNotBlank(payPaymentNo)) {
            jsonObject.put("pay_payment_no", payPaymentNo);
        }

        JSONObject responseJson = null;

        try {

            log.info("[ {} - requestBody is ] {} ", tradeId, jsonObject.toJSONString());
            String response = HttpClientTemplate.doPostBody(payBaseUrl + PAY_PAYMENT_QUERY_INFO_URL, jsonObject.toJSONString(), this.getRequestHead(venderId));

            log.info("[ {} - response is ] {}", tradeId, response);
            if (StringUtils.isBlank(response)) {
                return null;
            }
            JSONObject prepayResponse = JSON.parseObject(response);
            String ret = prepayResponse.getString("ret");
            if (ret.equals("0")) {
                responseJson = prepayResponse;

                log.info("{} - responseJson is {}.", tradeId, responseJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return responseJson;
    }

}
